<template>
  <div :class="{'mobile-detail-wrap':showMobilePage}">
    <template v-if="!permissionDenied">
      <div v-if="!showMobilePage || (historyOrderList && historyOrderList.length)" class="detail-top-container">
        <div v-if="!showMobilePage" class="title">订单详情</div>
        <div v-if="historyOrderList && historyOrderList.length" class="history-order-list">
          <div class="name">订单版本</div>
          <el-select v-model="curOrderId" size="small" @change="changeHistory">
            <el-option
              v-for="item in historyOrderList"
              :key="item.id"
              :value="item.id"
              :label="handelOrderName(item)"/>
          </el-select>
        </div>
        <div class="flex-item"/>
        <ListHeader v-if="!showMobilePage" />
      </div>
      <div v-loading="listLoading" class="no-padding order-detail">
        <div v-if="detailInfo" :class="{'mobile-el-form': showMobilePage}" class="box">
          <template v-if="detailInfo.orderInfo && detailInfo.orderInfo.orderType !== 9">
            <step v-if="!showMobilePage && detailInfo && detailInfo.orderStatus" :mode="2" :order-status="detailInfo.orderStatus" :is-show-correct="false" :node-approvers="handleNode"/>
            <div v-if="detailInfo && (detailInfo.orderStatus || detailInfo.orderStatus === 0)" class="status-msg-container">
              <div class="status-msg"><span class="title">当前订单状态为：</span><span class="content">{{ detailInfo.orderStatus | statusMsg }}</span> </div>
            </div>
          </template>
          <div v-if="detailInfo.orderInfo.orderType === 9" class="status-msg-container">
            <div class="status-msg"><span class="content">当前订单是最终单，展示原订单所有变更记录的最终结果</span> </div>
          </div>
          <!-- 媒介和内品无法查看客户信息 -->
          <clientInfoComponent
            v-if="isClientInfo"
            :is-client-info="isClientInfo"
            :client-info="clientInfo"
            :order-info="orderInfo"
            :configure-client-info="configureClientInfo"
            :class="{'dividing' : !showMobilePage}"
          />
          <orderInfoComponent
            ref="orderInfoRef"
            :order-info="orderInfo"
            :detail-info="detailInfo"
            :configure-detail-info="configureDetailInfo"
            :configure-order-info="configureOrderInfo"
            :class="{'dividing' : !showMobilePage}"
          />
          <resourceInfo
            v-if="detailInfo && orderInfo"
            :order-info="orderInfo"
            :detail-info="detailInfo"
            :configure-detail-info="configureDetailInfo"
            :configure-order-info="configureOrderInfo"
            :class="{'dividing' : !showMobilePage}"
          />
          <publishInfo
            v-if="detailInfo && orderInfo"
            ref="publishInfoRef"
            :order-info="orderInfo"
            :configure-order-info="configureOrderInfo"
            :detail-info="detailInfo"
            :class="{'dividing' : !showMobilePage}"
            @setIsLinkRequired="setIsLinkRequired" />
          <charge-off-record
            v-if="detailInfo && hasRouteAuth('crm:finance:read')"
            :disabled="detailInfo.orderInfo.orderType === 2 || detailInfo.isHedging"
            :records="detailInfo.financeRecord"
            :hide-all-operation="hideAllOperation"
            :is-not-add-account="hasRouteAuth('crm:orderList:addAccount')"
            :order-id="orderId"
            :order-status="detailInfo.orderStatus"
            :client-name="clientInfo.clientName"
            :client-id="clientInfo.clientId"
            title-size="16px"
            @getDetail="getInfo" />
          <div class="page-padding">
            <costBreakdownComponent
              v-if="detailInfo"
              ref="costBreakdownRef"
              :cost-breakdown="costBreakdown"
              :order-info="orderInfo"
              :order-id="orderId"
              :hide-all-operation="hideAllOperation"
              :show-settlement-btn="true"
              :order-num="orderInfo.orderId"
              :is-cost-info="isCostInfo"
              :is-cost-relate="isCostRelate"
              :sealing-disabled="firstsSealing"
              :cost-belong-type="0"
              :is-detail="true"
              :is-order="true"
              :order-status="detailInfo.orderStatus"
              :sealing-active="sealingActive"
              @update="update"
            />
          </div>
          <!-- 媒介和内品无法查看 -->
          <!-- <el-row v-if="invoiceInfo">
          <invoiceInfoComponent :invoice-info="invoiceInfo" />
        </el-row> -->
          <!-- 媒介和内品无法查看 -->
          <!-- <el-row v-if="contractInfo">
          <contractInfoComponent :contract-info="contractInfo" />
        </el-row> -->
          <!-- 媒介和内品无法查看 -->
          <div v-if="detailInfo" class="select-related-container">
            <InvoiceAndContract
              ref="ContractSelect"
              :show-empty="true"
              :is-edit="detailInfo.orderStatus < 5"
              :title="'合同信息'"
              :hide-all-operation="hideAllOperation"
              :sub-title="'关联合同'"
              :is-disabled="!isOtherInfo || detailInfo.orderInfo.orderType === 2"
              :type="1"
              title-size="16px"
              style="margin-top: 10px;"
              placeholder="请输入合同编号/合同名称"
              @changeSelect="changeSelect" />
          </div>
          <div v-if="detailInfo" class="invoice-container-outer page-padding">
            <InvoiceTable :table-data="detailInfo.invoiceInfo || []"/>
          </div>
          <div v-if="detailInfo" class="invoice-container-outer page-padding">
            <RelatedQueryOrder
              ref="relatedQueryOrderRef"
              :order-id="orderId"
              :related-style="{
                position: 'absolute',top: '-7px',right: '24px'
              }"
              :tip-text="'每个订单仅能关联一笔询单'"
              :show-related-btn="detailInfo.orderInfo.orderType !== 9"
              @cancelRelated="getInfo"
              @confirmRelatedQueryOrder="confirmRelatedQueryOrder"
            />
          </div>
          <!-- <div v-if="detailInfo" class="select-related-container">
            <div style="height:30px;display:flex;align-items:center;">
              <div><Title title="发票信息" /></div>
              <IconAmountLayout :amount="detailInfo.invoiceAmount/100" amount-text="有效发票金额" />
            </div>
            <InvoiceAndContract
              ref="InvoiceSelect"
              :is-edit="detailInfo.orderStatus < 5"
              :hide-all-operation="hideAllOperation"
              :show-empty="true"
              :related-contract-style="{
                position: 'absolute',top: '3px',right: '24px'
              }"
              :is-disabled="!isOtherInfo || detailInfo.orderInfo.orderType === 2"
              :type="2"
              title-size="16px"
              target-keyword="no"
              placeholder="请输入发票编号/发票号码"
              @changeSelect="changeSelect" />
          </div> -->
          <div style="margin-top: 32px;" class="page-padding">
            <Title :title="'操作记录'" font-size="16px" style="margin-bottom:10px;"/>
            <div v-if="operateLogs && operateLogs.length">
              <log-time-line :logs="operateLogs" :edit-api="editLogRemark" is-fold @success="editRemarkSuccess" />
            </div>
            <div v-else class="empty-container">
              <img :src="emptyImg" alt="">
              <div class="empty-text">暂无操作日志</div>
            </div>
          </div>
          <btnBar
            v-if="detailInfo"
            :is-disabled-without-micro="!isCostInfo"
            :is-disabled-micro="!isOtherInfo"
            :order-id="orderId"
            :detail-info="detailInfo"
            :score="score"
            :is-show-score-tip="isShowScoreTip"
            :score-tip-left="scoreTipLeft"
            :is-link-required="isLinkRequired"
            @closeScoreTip="closeScoreTip"
            @toScoreList="handleScore"
            @toSubmit="toSubmit"
            @getInfo="getInfo" />
        </div>
      </div>
    </template>
    <DeniedPlaceholder v-else class="denied-container"/>
    <scoreDialog
      ref="scoreDialogRef"
      :score="score"
      :list="scoreList"
      :business-id="orderId"
      :loading="scoreLoading"
      :show-mobile-page="showMobilePage"
      @updateScore="getOrderScoreList" />
  </div>

</template>
<script>
import emptyImg from '@/assets/empty-data-icon.png';
import { getOrderInfo, editOrder, changeTalent, getOperateReports, editLogRemark, relatedInvoiceAndContract, getOrderScoreList, queryOrderRelated } from '@/api/order';
import { hasRouteAuth } from '@/utils/permission';
import Title from '@/components/Title';
import ElMessage, { showModal } from '@/utils/message';
import { format } from '@/filters/date';
// compoents
import ListHeader from '@/components/Common/header/listHeader';
import scoreDialog from '@/components/CreateOrder/orderDetail/scoreDialog';
import clientInfoComponent from '@/components/CreateOrder/orderDetail/clientInfo';
import orderInfoComponent from '@/components/CreateOrder/orderDetail/orderInfo';
import resourceInfo from '@/components/CreateOrder/orderDetail/resourceInfo';
import publishInfo from '@/components/CreateOrder/orderDetail/publishInfo';
import costBreakdownComponent from '@/components/Cost/costList';
import contractInfoComponent from '@/components/CreateOrder/orderDetail/contractInfo';
import invoiceInfoComponent from '@/components/CreateOrder/orderDetail/invoiceInfo';
import btnBar from '@/components/CreateOrder/orderDetail/topBar';
import step from '@/components/CreateOrder/orderDetail/step';
import LogTimeLine from '@/components/Common/logTimeLine';
import RelatedQueryOrder from '@/components/RelatedQueryOrder';
import InvoiceAndContract from '@/components/CreateOrder/InvoiceAndContract';
import ChargeOffRecord from '@/components/CreateOrder/orderDetail/chargeOffRecord';
import { mapState } from 'vuex';
import { orderTypeStatusFilter } from '@/filters/status';
import FileShowList from '@/components/CreateOrder/fileShowList';
import { moneyFilter } from '@/filters/number';
import IconAmountLayout from '@/components/Common/IconAmountLayout';
import InvoiceTable from '@/components/Finance/invoiceTable';

export default {
  filters: {
    moneyFilter,
    statusMsg(status) {
      // 订单状态： 0: 草稿中 1: 待发布 2: 待核算 3: 待审批 4: 待封账 5: 封账中 6: 已封账 7: 已完成
      const msg = {
        '0': '草稿中，可通过订单编辑，填写必填项后提交订单',
        '1': '待发布，请添加发布链接、发布文案和发布截图并提交发布',
        '2': '待核算，请添加成本信息后提交成本核算',
        '3': '待审批，请仔细审批订单信息是否有误；若有错误可退回或通过编辑订单修改。',
        '4': '待封账，请在提交封账前及时核销流水、关联发票合同。',
        '5': '封账中，已完成的流水不可撤回。当前添加的流水不会加入封账中。',
        '6': '已封账，可继续核销待核销的流水。',
        '7': '已完成，订单所有流水已核对，交易完成；该订单业绩已生效'
      };
      return msg[status + ''];
    }
  },
  components: {
    Title,
    ListHeader,
    FileShowList,
    contractInfoComponent,
    invoiceInfoComponent,
    clientInfoComponent,
    orderInfoComponent,
    costBreakdownComponent,
    ChargeOffRecord,
    LogTimeLine,
    resourceInfo, InvoiceAndContract,
    publishInfo, btnBar, step, IconAmountLayout,
    InvoiceTable, scoreDialog, RelatedQueryOrder
  },
  data() {
    return {
      orderId: '',
      orderInfo: {},
      configureOrderInfo: {},
      configureCostBreakdown: {},
      clientInfo: {},
      configureClientInfo: null,
      operateLogs: [],
      invoiceInfo: null,
      contractInfo: null,
      detailInfo: null,
      configureDetailInfo: null,
      btnLoading: false,
      listLoading: false,
      permissionDenied: false, // 详情页是否可查看
      emptyImg,
      costBreakdown: {
        page: 1,
        perPage: 20,
        costList: [],
        total: 0
      },
      sealingDisabled: false,
      sealingActive: false,
      firstsSealing: false,
      curOrderId: '',
      historyOrderList: [],
      score: null,
      scoreList: [],
      scoreLoading: false,
      isShowScoreTip: false,
      scoreTipLeft: null,
      isLinkRequired: false
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo,
      'showMobilePage': state => state.app.showMobilePage,
      'sidebar': state => state.app.sidebar
    }),
    /**
      - 客户信息查看/编辑：勾选状态下，可 查看/编辑 订单用户信息(含列表、详情)
      - 发布信息编辑：勾选状态下，可 编辑 下单链接/上传文件信息：
      - 成本信息编辑：勾选状态下，可 编辑 除微任务成本/ID外的成本信息
      - 其他信息编辑：勾选状态下，可 编辑 除客户、发布、成本外的信息
    */
    isClientInfo() {
      return hasRouteAuth('crm:orderList:clientInfo');
    },
    isCostInfo() {
      return hasRouteAuth('crm:orderList:costInfo');
    },
    isCostRelate() {
      return hasRouteAuth('crm:orderList:relateCost');
    },
    isOtherInfo() {
      return hasRouteAuth('crm:orderList:otherInfo');
    },
    hideAllOperation() {
      // 对冲单(2) 和 最终单(9) 不可以进行任何操作
      const orderType = this.detailInfo.orderInfo.orderType;
      return orderType === 9 || orderType === 2;
    },
    relatedEdit() {
      const item = this.detailInfo;
      if (!item) return false;
      if (this.userInfo.userName === '管理员') return true; // 管理员
      if (hasRouteAuth('crm:orderList:admin')) return true; // 全向展示
      let haveOrderOperator = false; // 当前登录的用户是否在该条订单的执行人中
      if (item.orderInfo.orderOperator) {
        haveOrderOperator = item.orderInfo.orderOperator.some(i => {
          return i.id === this.userInfo.id;
        });
      }
      let haveOrderMarket = false; // 是否是当前销售
      if (item.clientInfo.marketId) {
        haveOrderMarket = this.userInfo.id === item.clientInfo.marketId;
      }
      let cooperationDepartmentIds = []; // 协作部门ID
      if (item.orderInfo.cooperationDepartment && item.orderInfo.cooperationDepartment.length) {
        cooperationDepartmentIds = item.orderInfo.cooperationDepartment.map(i => i.id);
      }
      const departmentId = item.attributionMatrixId;
      let departmentAuth = false; // 拥有部门全向编辑，当前登录的用户存在该条订单的部门中,或者协作部门中
      const isNoOperator = !item.orderInfo.orderOperator || item.orderInfo.orderOperator.length === 0;
      if (hasRouteAuth('crm:orderList:adminEdit') || isNoOperator) {
        const deptName = this.userInfo.deptName;
        departmentAuth = deptName.some(i => {
          return departmentId === i.id || cooperationDepartmentIds.includes(i.id);
        });
      }
      return haveOrderOperator || haveOrderMarket || departmentAuth;
    },
    handleNode() {
      const arr = this.detailInfo.nodeApprovers.slice(0);
      arr.forEach(el => {
        if (el.length > 1) {
          el.forEach(item => {
            item.processStatus = item.processStatus >= 3 ? (item.processStatus - 2) : (item.processStatus - 1);// 由于某个版本去掉第二步骤，所以需要做处理
          });
        } else {
          el[0].processStatus = el[0].processStatus >= 3 ? (el[0].processStatus - 2) : (el[0].processStatus - 1);
        }
      });
      return arr;
    }
  },
  watch: {
    sidebar: {
      handler(v) {
        // 菜单展开收起时重新计算评分提示的位置
        if (!this.showMobilePage) {
          this.scoreTip();
        }
      },
      deep: true
    }
  },
  created() {
    this.orderId = Number(this.$route.params.orderId) || '';
    this.curOrderId = this.orderId;
    const sealingId = Number(this.$route.query.sealingId) || null;
    this.firstsSealing = Boolean(sealingId); // v2.8新增 用于判断如果是从销售初审的入口进去的话，成本明细允许进行编辑,删除，关联
    const sealingActive = Number(this.$route.query.active) || null;
    this.sealingActive = sealingActive === 2; // v2.8新增 用于判断如果是从销售初审还是从财务复审的入口进去的话，财务复审的话成本明细允许进行编辑,删除，关联
    this.getInfo().then(res => {
      const configureId = res ? res.orderInfo.configureId : null;
      // orderType: 2(对冲单)  8(变更单)  9(最终单)
      if (configureId && res.orderInfo.orderType === 8) {
        this.getConfigureInfo(configureId);
      }
      if (this.detailInfo.orderStatus && this.detailInfo.orderStatus > 1) {
        this.getOrderScoreList();
      }
    });
  },
  methods: {
    editLogRemark,
    hasRouteAuth,
    update() {
      this.getInfo();
    },
    handleScore() {
      this.$refs['scoreDialogRef'].openDialog();
    },
    setIsLinkRequired(val) {
      this.isLinkRequired = val;
    },
    scoreTip() {
      if (this.detailInfo && this.detailInfo.orderStatus && this.detailInfo.orderStatus === 7) {
        let myData = [];
        if (this.scoreList.length) {
          myData = this.scoreList.filter(it => it.userId === this.userInfo.id);
        }
        this.isShowScoreTip = !myData.length;
        if (!myData.length) {
          this.setScoreBtnPosition();
        }
      }
    },
    confirmRelatedQueryOrder(id) {
      const params = {
        ids: String(this.orderId),
        id
      };
      queryOrderRelated(params).then(res => {
        if (res.code === 200) {
          // if (this.$refs.relatedQueryOrderRef) this.$refs.relatedQueryOrderRef.init();
          this.detailInfo.queryOrderId = id;
          this.$message.success('操作成功');
        }
      }).catch(error => console.error(error));
    },
    setScoreBtnPosition() {
      this.$nextTick(() => {
        const el = document.querySelector('.score-btn');
        this.scoreTipLeft = el.offsetLeft - 50;
      });
    },
    closeScoreTip() {
      this.isShowScoreTip = false;
    },
    getOrderScoreList() {
      const params = {
        businessId: this.orderId
      };
      this.scoreLoading = true;
      getOrderScoreList(params).then(res => {
        if (res.code === 200) {
          this.score = res.data.score;
          this.scoreList = res.data.list;
          this.scoreLoading = false;
          this.$nextTick(() => {
            this.scoreTip();
          });
        }
      }).catch(err => {
        console.error(err.message);
        this.scoreLoading = false;
      });
    },
    // 保存
    toSubmit({ isValidate = true, muted = false, loading = true }, callback) {
      const resourceParams = this.$refs.orderInfoRef ? this.$refs.orderInfoRef.getParams() : {};
      const publishParams = this.$refs.publishInfoRef ? this.$refs.publishInfoRef.getParams() : {};
      const costParams = this.$refs.discountInfoRef ? this.$refs.discountInfoRef.getParams() : null;
      const params = _.cloneDeep(this.detailInfo);
      params.saveDraft = !isValidate;
      // 资源信息
      params.orderInfo.orderOperator = resourceParams.orderOperator;
      params.orderInfo.orderBusinessOperator = resourceParams.orderBusinessOperator;
      params.orderInfo.orderResourceOperator = resourceParams.orderResourceOperator;
      params.orderInfo.cooperationDepartment = resourceParams.cooperationDepartment;
      // 发布信息
      params.publishInfo = publishParams;
      // 发票和合同
      const relatedIds = this.getRelatedIds();
      params.invoiceIds = relatedIds.invoiceIds;
      params.contractIds = relatedIds.contractIds;
      if (costParams) params.costBreakdown = costParams;
      const validatePromise = [];
      if (this.$refs.discountInfoRef) validatePromise.push(this.$refs.discountInfoRef.validateForm(true));
      if (this.$refs.publishInfoRef) validatePromise.push(this.$refs.publishInfoRef.validateForm(true));

      if (validatePromise.length > 0) {
        Promise.all(validatePromise).then(res => {
          this.editOrder(params, muted, loading, callback);
        }).catch(() => {
          ElMessage.warning('请检查信息是否填写完整');
        });
      } else {
        this.editOrder(params, muted, loading, callback);
      }
    },
    // 判断达人分成计算后的值是否和原来的值不一样，不一样则提示
    judgeTalent(oldTalentNum, newTalentNum, showTip) {
      return new Promise((resolve, reject) => {
        if (showTip) {
          if (oldTalentNum !== newTalentNum) {
            showModal(
              `<div style="margin-bottom: 13px;">达人成本变更提示</div>
              <div style="line-height: 1.3;">订单信息更改，达人成本由<span style="color: red">${oldTalentNum}</span>变更为<span style="color: red">${newTalentNum}</span>请确认是否更新达人成本</div>
              `, '',
              {
                confirmButtonText: '保存并更新成本',
                cancelButtonText: '仅保存订单',
                type: 'warning',
                dangerouslyUseHTMLString: true,
                lockScroll: false,
                center: true,
                customClass: 'del-message del-message-cancel message-react-btn',
                iconClass: 'del-icon'
              }, true).then(() => {
              changeTalent({ id: this.orderId }).then(res => {
                resolve();
              }).catch(() => {
                resolve();
              });
            }).catch(() => {
              resolve();
            });
          } else {
            resolve();
          }
        } else {
          changeTalent({ id: this.orderId }).then(res => {
            resolve();
          }).catch(() => {
            resolve();
          });
        }
      });
    },
    editOrder(params, muted, loading, callback) {
      if (!muted) this.btnLoading = true;
      editOrder(this.orderId, params).then((res) => {
        this.btnLoading = false;
        if (callback) callback();
        const oldTalentNum = res.data ? res.data.oldTalentNum || 0 : 0;
        const newTalentNum = res.data ? res.data.newTalentNum || 0 : 0;
        if (params.costBreakdown.isAutoTalent === 1 && (oldTalentNum !== newTalentNum)) {
          // 1.待核算保存(2)、待审批编辑订单保存、销售初审编辑订单保存。提示达人成本新旧数据
          const showTip = this.detailInfo.orderStatus === 2;
          this.judgeTalent(oldTalentNum, newTalentNum, showTip).then(() => {
            this.editAfter(muted, loading);
          });
        } else {
          this.editAfter(muted, loading);
        }
      }, result => {
        this.btnLoading = false;
        // this.$message.error(result.message);
      });
    },
    editAfter(muted, loading) {
      if (!muted) ElMessage.success('修改成功');
      this.getInfo(loading);
    },
    // 获取合同和发票
    getRelatedIds() {
      const contractSelect = this.$refs.ContractSelect;
      const invoiceSelect = this.$refs.InvoiceSelect;
      let contractIds = [];
      let invoiceIds = [];
      if (contractSelect && contractSelect.selectData) {
        contractIds = contractSelect.selectData.map(i => i.id);
      }
      if (invoiceSelect && invoiceSelect.selectData) {
        invoiceIds = invoiceSelect.selectData.map(i => i.id);
      }
      return {
        contractIds: contractIds.join(','),
        invoiceIds: invoiceIds.join(',')
      };
    },
    // 合同和发票修改
    changeSelect(selectData) {
      // const isDraft = this.detailInfo.orderStatus === 0;
      // this.toSubmit({ isValidate: !isDraft, muted: true });
      // 发票和合同
      const params = {
        id: this.orderId
      };
      const relatedIds = this.getRelatedIds();
      params.invoiceIds = relatedIds.invoiceIds;
      params.contractIds = relatedIds.contractIds;
      relatedInvoiceAndContract(params).then(res => {
        if (res.code === 200) {
          this.getInfo();
        } else {
          this.$message.error(res.message);
        }
      });
    },
    getConfigureInfo(configureId) { // 调整单对比信息
      getOrderInfo(configureId).then((res) => {
        this.configureDetailInfo = res.data;
        if (res.data.orderInfo.orderKind && res.data.orderInfo.orderKind.length) res.data.orderInfo.orderKindName = res.data.orderInfo.orderKind.map(i => i.orderKindName).join('，');
        this.configureOrderInfo = res.data.orderInfo;
        this.configureCostBreakdown = res.data.costBreakdown;
        this.configureClientInfo = res.data.clientInfo;
        // this.invoiceInfo = res.data.invoiceInfo;
        // this.contractInfo = res.data.contract;
      }).catch(e => {
        this.listLoading = false;
        console.error(e);
      });
    },
    getInfo(loading = true) {
      this.listLoading = loading && true;
      return new Promise((resolve, reject) => {
        getOrderInfo(this.orderId).then((res) => {
          if (res.data && res.data.publishInfo) {
            res.data.publishInfo.autoPick = res.data.publishInfo.autoPick || false;
            const status = res.data.publishInfo.status;
            res.data.publishInfo.status = status || status === 0 ? status : '';
          } else {
            res.data.publishInfo.status = '';
            res.data.publishInfo.autoPick = false;
          }
          this.historyOrderList = res.data.historyOrderList || [];
          this.listLoading = false;
          this.detailInfo = res.data;
          if (res.data.orderInfo.orderKind && res.data.orderInfo.orderKind.length) res.data.orderInfo.orderKindName = res.data.orderInfo.orderKind.map(i => i.orderKindName).join('，');
          res.data.orderInfo.orderStatus = res.data.orderStatus;
          this.orderInfo = res.data.orderInfo;
          this.costBreakdown.costList = res.data.costBreakdown.costList;
          this.costBreakdown.total = res.data.costBreakdown.costList.length;
          this.clientInfo = res.data.clientInfo;
          this.invoiceInfo = res.data.invoiceInfo;
          this.contractInfo = res.data.contract;
          if (res.data.queryOrderInfo) {
            this.detailInfo.queryOrderId = res.data.queryOrderInfo.id;
          }
          // test
          this.orderInfo.priceTable = [{
            name: '含税',
            planPrice: this.orderInfo.planPrice === null ? '--' : (this.orderInfo.planPrice / 100).toFixed(2),
            channelPrice: this.orderInfo.channelPrice === null ? '--' : (this.orderInfo.channelPrice / 100).toFixed(2),
            totalPrice: this.orderInfo.taxAmount === null ? '--' : (this.orderInfo.taxAmount / 100).toFixed(2),
            disabled: false
          }, {
            name: '刊例',
            planPrice: this.orderInfo.articlesPlanPrice === null ? '--' : (this.orderInfo.articlesPlanPrice / 100).toFixed(2),
            channelPrice: this.orderInfo.articlesChannelPrice === null ? '--' : (this.orderInfo.articlesChannelPrice / 100).toFixed(2),
            totalPrice: this.orderInfo.articlesPrice === null ? '--' : (this.orderInfo.articlesPrice / 100).toFixed(2),
            disabled: false
          }, {
            name: '折扣',
            planPrice: this.orderInfo.planDiscountPrice === null ? '--' : this.orderInfo.planDiscountPrice,
            channelPrice: this.orderInfo.channelDiscountPrice === null ? '--' : this.orderInfo.channelDiscountPrice,
            totalPrice: this.orderInfo.discountPrice === null ? '--' : this.orderInfo.discountPrice,
            disabled: true
          }];
          if (res.code === 200) {
            this.getOperateReports();
          }
          this.$nextTick(() => {
            if (this.$refs.costBreakdownRef) this.$refs.costBreakdownRef.insertDetail(res.data.costBreakdown);
            if (this.$refs.discountInfoRef) this.$refs.discountInfoRef.insertDetail(res.data);
            if (this.$refs.ContractSelect) this.$refs.ContractSelect.setDefault(res.data.contract);
            if (this.$refs.InvoiceSelect) this.$refs.InvoiceSelect.setDefault(res.data.invoiceInfo);
            if (this.$refs.relatedQueryOrderRef) this.$refs.relatedQueryOrderRef.setDefault(res.data.queryOrderInfo);
          });
          resolve(res.data);
        }).catch(e => {
          if (e.code === 403) {
            this.permissionDenied = true;
          }
          this.listLoading = false;
          console.error(e);
          reject(e);
        });
      });
    },
    getOperateReports() {
      const data = {
        id: this.orderId,
        type: 0
      };
      getOperateReports(data).then(res => {
        if (res.code === 200) {
          this.operateLogs = res.data;
        }
      });
    },
    editRemarkSuccess() {
      this.getOperateReports();
    },
    changeHistory(val) {
      this.orderId = val;
      this.configureDetailInfo = null;
      this.configureOrderInfo = null;
      this.configureCostBreakdown = null;
      this.configureClientInfo = null;
      this.getInfo().then(res => {
        const configureId = res ? res.orderInfo.configureId : null;
        // orderType: 2(对冲单)  8(变更单)  9(最终单)
        if (configureId && res.orderInfo.orderType === 8) {
          this.getConfigureInfo(configureId);
        }
        this.getOrderScoreList();
      });
    },
    handelOrderName(item) {
      let ans = orderTypeStatusFilter(item.orderType);
      if (item.createTime) {
        const time = format(item.createTime, 'YYYY/MM/DD');
        ans += `-${time}`;
      }
      if (item.createName) {
        ans += `-${item.createName}`;
      }
      return ans;
    }
  }
};
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.suspend-btn {
  position: fixed;
  right: 16px;
  top: 50%;
  z-index: 2001;
  width: 48px;
  height: 48px;
  display: flex;
  align-items: center;
  justify-content: center;;
  border-top-left-radius: 8px;
  border-bottom-left-radius: 8px;
  color: #fff;
  cursor: pointer;
  background: linear-gradient(163deg, #93ADFF 0%, #2754E2 100%);
  box-shadow: 0px 3px 7px rgba(39, 84, 226, 0.31);
  &.is-mobile {
    right: 0;
  }
  .icon {
    font-size: 16px;
    font-weight: 500;
  }
  .text {
    font-size: 12px;
    text-align: center;
    width: 24px;
  }
  .suspend-btn-img {
    width: 14px;
    height: 17px;
  }
}
.order-detail {
  padding: 16px;
  min-height: 300px;
  .box {
    overflow: hidden;
    position: relative;
    background-color: #fff;
    padding-bottom: 100px;
    &::v-deep {
      .detail-row {
        .el-form {
          .el-form-item {
            &:not(.mb10) {
              margin-bottom: 0px !important;
            }
            padding-right: 10px;
            .el-form-item__content {
              white-space: nowrap;
              overflow: hidden;
              text-overflow: ellipsis;
            }
          }
        }
      }
      .dividing{
        .el-col {
          .el-form-item__content {
            border-right: 1px solid #EBEEFD;
          }
          &:nth-child(3n) {
            .el-form-item__content {
              border-right: none;
            }
          }
          &:last-child {
            .el-form-item__content {
              border-right: none;
            }
          }
        }
      }
    }

    .el-row {
      .el-form {
        & > .el-col-24 {
          padding: 0 10px 0 0px;
          box-sizing: border-box;
          .el-col-24 {
            margin: 0;
          }
        }
        .el-form-item {
          padding-right: 10px;
        }
      }
      .el-card {
        border: none;
        background: #fff;
        // border-radius: 12px;
        // box-shadow:2px 4px 13px 0px rgba(221,225,234,1);
        border-radius: 0;
        box-shadow: none;
        .el-card__body {
          padding: 0;
        }
      }
      .title {
        font-size: 12px;
        color: #515151;
        font-weight: bold;
        border-bottom: 1px solid #e4e4e4;
        padding: 10px 12px;
      }
      .original-order {
        color: #55a7d2;
      }
    }
  }
  .to-back {
    width: 120px;
    background:rgba(239,243,251,1);
    border: none;
    border-radius:4px;
    font-size:16px;
    font-weight:400;
    color:rgba(64,110,255,1);
    line-height:16px;
  }
  .to-back-edit {
    margin: 0 0 32px 32px;
    width: 120px;
    background:rgba(64,110,255,1);
    border: none;
    border-radius:4px;
    font-size:16px;
    font-weight:400;
    color:#fff;
    line-height:16px;
  }
  .charge-off-record {
    margin-top: 32px;
  }
}
.log-open-btn {
  display:flex;
  justify-content:center;
  color: #333333;
  font-size:14px;
  cursor: pointer;
  align-items: center;
  margin-top: 10px;
  i {
    margin-left: 8px;
  }
}
.resource-link {
  word-break:break-all;
}
.status-msg-container {
  background-color: #F9F9F9;
  padding: 0 24px;
}
.status-msg {
  padding: 9px 0;
  .title {
    font-size: 13px;
    color: #141C3D;
    line-height: 16px;
  }
  .content {
    font-size: 13px;
    color: #141C3D;
    line-height: 16px;
  }
}
.create-container {
  border-radius: 0 !important;
  box-shadow: none !important;
  padding: 24px 24px 0 24px !important;
  margin-bottom: 10px;
  & ::v-deep {
    .el-input__inner  {
      width: 240px;
      line-height: 16px;
    }
    .el-form-item {
      margin-bottom: 32px;
    }
    .el-date-editor.el-input {
      width: 240px;
    }
  }
}
.select-related-container {
  padding: 0px 24px;
  margin-top: 32px;
  position: relative;
  &::v-deep {
    .el-input__inner  {
      width: 240px;
      line-height: 16px;
    }
  }
}
.invoice-container-outer {
  margin-top: 32px;
  position: relative;
}
.foot {
  position: absolute;
  width: 100%;
  z-index: 101;
  background: #FBFBFD;
  height: 24px;
  left: 0;
  bottom: 0;
}
.empty-container {
  text-align: center;
  position: relative;
  margin-top: 20px;
  img {
    width: 90px;
  }
  .empty-text {
    color: #999;
    max-width: 300px;
    font-size: 14px;
    margin: 0 auto;
  }
}
.detail-top-container {
  display: flex;
  align-items: center;
  width: 100%;
  background-color: #fff;
  padding-right: 16px;
  padding-left: 16px;
  height: 48px;
  .title {
    font-size: 16px;
    line-height: 1.5;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    color: #333333;
  }
  .flex-item {
    flex:1;
  }
  .history-order-list {
    display: flex;
    align-items: center;
    margin-left: 39px;
    .name {
      color: #666666;
      font-size: 14px;
      font-family: PingFangSC-Regular;
      line-height: 14px;
      margin-right: 20px;
    }
    &::v-deep {
      .el-select  {
        width: 240px;
        .el-select__caret {
          color: #333;
        }
      }
    }
  }
}
.page-padding {
  padding:0 24px;
}
.denied-container {
  height: 100vh;
  justify-content: flex-start;
  padding-top: 100px;
}
.mobile-detail-wrap {
  .history-order-list {
    margin-left: 0px;
  }
  &::v-deep {
    .detail-row,.charge-off-record,.page-padding,.select-related-container,.status-msg-container,.detail-top-container {
      padding-left: 12px !important;
      padding-right: 12px !important;
    }
  }
}
</style>
